<template>
	<view class="order-list-container">
		<!-- 导航栏 -->
		<nav-bar></nav-bar>
		<!-- 订单状态导航 -->
		<scroll-view class="status-nav" scroll-x show-scrollbar="false">
			<view class="nav-item" v-for="(item, index) in statusOptions" :key="index"
				:class="{ active: currentStatus === item.value }" @tap="switchStatus(item.value)">
				<text>{{ item.label }}</text>
				<view class="active-line" v-if="currentStatus === item.value"></view>
			</view>
		</scroll-view>

		<!-- 订单列表 -->
		<scroll-view class="order-list" scroll-y>
			<view class="order-item" v-for="order in filteredOrders" :key="order.id">
				<view class="order-header">
					<text class="order-no">订单号：{{ order.orderNo }}</text>
					<text class="order-status" :class="'status-' + order.orderStatus">{{ getOrderStatus(order.orderStatus) }}</text>
				</view>

				<!-- 商品列表 -->
				<view class="product-list" v-if="getOrderItems(order).length > 0">
					<view class="product-item" v-for="(item, index) in getOrderItems(order)" :key="index">
						<image class="product-image" :src="item.productImage" mode="aspectFit"></image>
						<view class="product-info">
							<view class="product-title">{{ item.productTitle }}</view>
							<view class="product-spec" v-if="item.specification">规格：{{ item.specification }}</view>
							<view class="product-price">¥{{ item.price }} × {{ item.quantity }}</view>
						</view>
					</view>
				</view>

				<view class="order-content">
					<view class="address-info">
						<text class="label">收货地址：</text>
						<text class="value">{{ order.receiverAddress }} {{ order.houseNumber }}</text>
					</view>
					<view class="receiver-info">
						<text class="label">收货人：</text>
						<text class="value">{{ order.receiverName }} {{ order.receiverPhone }}</text>
					</view>
					<view class="price-info">
						<text class="label">订单金额：</text>
						<text class="value price">¥{{ order.totalAmount }}</text>
					</view>
					<view class="time-info">
						<text class="label">下单时间：</text>
						<text class="value">{{ formatTime(order.createTime) }}</text>
					</view>
				</view>

				<!-- 添加支付按钮 -->
				<view class="order-footer" v-if="order.payStatus === 0">
					<button class="pay-btn" @tap="goToPay(order)">去支付</button>
					<button class="cancel-btn" @tap="cancelOrder(order)">取消订单</button>
				</view>
			</view>

			<!-- 无数据提示 -->
			<view class="empty-tip" v-if="filteredOrders.length === 0">
				{{ loading ? '加载中...' : currentStatus === null ? '暂无订单数据' : '暂无相关状态的订单' }}
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import NavBar from '@/components/nav-bar/nav-bar.vue'
	export default {
		components: {
			NavBar
		},
		data() {
			return {
				orders: [],
				loading: false,
				currentStatus: null, // null表示全部
				statusOptions: [{
						label: '全部',
						value: null
					},
					{
						label: '待付款',
						value: 0
					},
					{
						label: '待发货',
						value: 1
					},
					{
						label: '已发货',
						value: 2
					},
					{
						label: '已完成',
						value: 3
					},
					{
						label: '已取消',
						value: 4
					},
					{
						label: '已退款',
						value: 5
					}
				]
			}
		},
		computed: {
			// 根据状态过滤订单
			filteredOrders() {
				if (this.currentStatus === null) {
					return this.orders
				}

				// 特殊处理待付款状态：orderStatus=0 且 payStatus=0
				if (this.currentStatus === 0) {
					return this.orders.filter(order => order.orderStatus === 0 && order.payStatus === 0)
				}

				return this.orders.filter(order => order.orderStatus === this.currentStatus)
			}
		},
		onLoad(options) {
			this.getOrderList()

			// 处理支付结果
			if (options && options.paymentResult === 'success') {
				// 从缓存获取支付结果
				try {
					const paymentResult = uni.getStorageSync('paymentResult')
					if (paymentResult && paymentResult.success && paymentResult.sourcePageData) {
						this.handlePaymentSuccess(paymentResult)
						// 清除支付结果缓存
						uni.removeStorageSync('paymentResult')
					}
				} catch (e) {
					console.error('处理支付结果失败:', e)
				}
			}
		},
		methods: {
			async getOrderList() {
				if (this.loading) return
				this.loading = true

				uni.showLoading({
					title: '加载中...'
				})

				try {
					const techId = uni.getStorageSync('userInfo').techId
					if (!techId) {
						uni.showToast({
							title: '用户信息不完整，请重新登录',
							icon: 'none'
						})
						this.loading = false
						uni.hideLoading()
						uni.stopPullDownRefresh()
						return
					}

					const res = await uni.request({
						url: `${uni.$config.baseUrl}/supplieOrder/supplieOrder/listAll`,
						method: 'GET',
						data: {
							techId: techId
						}
					})

					if (res.statusCode === 200 && res.data.code === 200) {
						const orderList = res.data.rows || []
						console.log('获取订单列表成功，共', orderList.length, '条订单')

						// 获取每个订单的详细信息
						this.orders = orderList // 先设置原始数据，确保有基本信息显示

						// 依次获取每个订单的详情
						for (let i = 0; i < orderList.length; i++) {
							try {
								const detailRes = await uni.request({
									url: `${uni.$config.baseUrl}/supplieOrder/supplieOrder/${orderList[i].id}`,
									method: 'GET'
								})

								if (detailRes.statusCode === 200 && detailRes.data.code === 200 && detailRes.data
									.data) {
									// 替换原始订单数据
									this.orders[i] = detailRes.data.data
									console.log(`订单 ${orderList[i].orderNo} 详情:`, detailRes.data.data)

									// 检查是否有商品信息
									if (detailRes.data.data.suppliesOrderItems) {
										console.log(
											`订单 ${orderList[i].orderNo} 包含 ${detailRes.data.data.suppliesOrderItems.length} 个商品`
										)
									} else {
										console.log(`订单 ${orderList[i].orderNo} 没有商品信息`)
									}
								}
							} catch (err) {
								console.error(`获取订单 ${orderList[i].orderNo} 详情失败:`, err)
							}
						}
					} else {
						console.error('获取订单列表失败:', res.data)
						uni.showToast({
							title: res.data.msg || '获取订单列表失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('获取订单列表失败:', error)
					uni.showToast({
						title: '获取订单列表失败',
						icon: 'none'
					})
				} finally {
					// 无论成功还是失败，都需要执行
					this.loading = false
					uni.hideLoading()
					uni.stopPullDownRefresh()
				}
			},

			getOrderStatus(status) {
				const statusMap = {
					0: '待付款',
					1: '待发货',
					2: '待收货',
					3: '已完成',
					4: '已取消'
				}
				return statusMap[status] || '未知状态'
			},

			formatTime(time) {
				if (!time) return ''
				const date = new Date(time)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
			},

			// 去支付
			goToPay(order) {
				uni.showLoading({
					title: '加载中...'
				});

				// 先获取订单详情，获取prepay_id
				uni.request({
					url: `${uni.$config.baseUrl}/supplieOrder/supplieOrder/${order.id}`,
					method: 'GET',
					success: (res) => {
						uni.hideLoading();
						if (res.statusCode === 200 && res.data.code === 200 && res.data.data) {
							const orderDetail = res.data.data;
							// 更新订单数据，包括商品列表
							if (orderDetail.suppliesOrderItems) {
								// 找到当前订单并更新
								const currentOrderIndex = this.orders.findIndex(o => o.id === order.id);
								if (currentOrderIndex !== -1) {
									this.orders[currentOrderIndex] = orderDetail;
								}
							}

							// 构建支付参数
							const paymentData = {
								amount: order.totalAmount,
								orderType: 4, // 4-物资订单
								orderDesc: `物料订单支付`,
								callbackUrl: '/pages/technician/mysupplieOrder?a=1', // 支付完成后的回调页面
								sourcePageData: {
									orderId: order.id,
									orderNo: order.orderNo
								},
								paymentParams: {
									orderId: order.id,
									orderNo: order.orderNo,
									paymentMethod: 1, // 1-微信支付
									orderType: 4, // 4-物资订单
									orderSource: 1 // 1-H5
								}
							};

							// 如果有prepayId，添加到支付参数
							if (orderDetail.prepayId) {
								paymentData.paymentParams.prepayId = orderDetail.prepayId;
								paymentData.paymentParams.timeStamp = orderDetail.timeStamp || String(Math
									.floor(Date.now() / 1000));
								paymentData.paymentParams.nonceStr = orderDetail.nonceStr || this
									.generateNonceStr();
								paymentData.paymentParams.package = `prepay_id=${orderDetail.prepayId}`;
								paymentData.paymentParams.signType = 'RSA';
								paymentData.paymentParams.paySign = orderDetail.paySign;
								console.log('已添加prepayId到支付参数:', orderDetail.prepayId);
							}

							// 使用缓存存储支付参数
							uni.setStorageSync('paymentData', paymentData);
							console.log('已将支付数据存入缓存');

							// 跳转到统一支付页面
							uni.navigateTo({
								url: `/pages/pay-public/pay-public?login=false`
							});
						} else {
							uni.showToast({
								title: res.data.msg || '获取订单信息失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('获取订单详情失败:', err);
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
					}
				});
			},

			// 生成随机字符串
			generateNonceStr(length = 32) {
				const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
				let result = '';
				for (let i = 0; i < length; i++) {
					result += chars.charAt(Math.floor(Math.random() * chars.length));
				}
				return result;
			},

			// 更新订单支付状态
			updateOrderPaymentStatus(orderId, paymentStatus) {
				if (!orderId) {
					console.error('订单ID不能为空')
					return
				}
				uni.request({
					url: `${uni.$config.baseUrl}/supplieOrder/supplieOrder/updatePaymentStatus`,
					method: 'POST',
					data: {
						orderId: orderId,
						paymentStatus: paymentStatus
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							console.log('订单支付状态更新成功')
							// 更新本地订单状态
							const order = this.orders.find(o => o.id === orderId);
							if (order) {
								order.payStatus = paymentStatus;
							}
						} else {
							console.error('订单支付状态更新失败:', res.data.message || '未知错误')
						}
					},
					fail: (err) => {
						console.error('更新订单支付状态请求失败:', err)
					}
				})
			},

			// 取消订单
			cancelOrder(order) {
				uni.showModal({
					title: '提示',
					content: '确定要取消该订单吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '取消中...'
							});

							uni.request({
								url: `${uni.$config.baseUrl}/supplieOrder/supplieOrder/${order.id}`,
								method: 'DELETE',
								success: (res) => {
									uni.hideLoading();
									if (res.statusCode === 200 && res.data.code === 200) {
										uni.showToast({
											title: '订单已取消',
											icon: 'success'
										});
										// 刷新订单列表
										this.getOrderList();
									} else {
										uni.showToast({
											title: res.data.msg || '取消订单失败',
											icon: 'none'
										});
									}
								},
								fail: (err) => {
									uni.hideLoading();
									console.error('取消订单失败:', err);
									uni.showToast({
										title: '取消订单失败',
										icon: 'none'
									});
								}
							});
						}
					}
				});
			},

			// 切换订单状态
			switchStatus(status) {
				this.currentStatus = status
				// 切换tab时可以选择刷新数据
				this.getOrderList()
			},

			onPullDownRefresh() {
				this.getOrderList()
			},

			// 处理支付成功
			handlePaymentSuccess(paymentResult) {
				if (paymentResult.sourcePageData && paymentResult.sourcePageData.orderId) {
					// 支付成功，更新订单支付状态
					this.updateOrderPaymentStatus(paymentResult.sourcePageData.orderId, 1)

					uni.showToast({
						title: '支付成功',
						icon: 'success',
						duration: 2000,
						success: () => {
							// 刷新订单列表
							setTimeout(() => {
								this.getOrderList()
							}, 2000)
						}
					})
				}
			},

			getOrderItems(order) {
				// 直接检查suppliesOrderItems数组
				if (order.suppliesOrderItems && Array.isArray(order.suppliesOrderItems) && order.suppliesOrderItems
					.length > 0) {
					return order.suppliesOrderItems;
				}

				// 检查是否在supplies对象内
				if (order.supplies && order.supplies.suppliesOrderItems && Array.isArray(order.supplies
						.suppliesOrderItems)) {
					return order.supplies.suppliesOrderItems;
				}

				// 检查可能的拼写变体
				if (order.supplieOrderItems && Array.isArray(order.supplieOrderItems)) {
					return order.supplieOrderItems;
				}

				// 尝试从订单直接获取商品信息（如示例数据所示）
				if (order.supplies) {
					return [{
						productImage: order.supplies.image,
						productTitle: order.supplies.title,
						specification: order.supplies.specifications,
						price: order.supplies.price,
						quantity: 1
					}];
				}

				// 没有找到商品信息
				return [];
			},
		}
	}
</script>

<style lang="scss" scoped>
	.order-list-container {
		min-height: 100vh;
		background: #F5F5F5;
		padding: 20rpx;
	}

	.order-list {
		.order-item {
			background: #FFFFFF;
			border-radius: 12rpx;
			margin-bottom: 20rpx;
			padding: 20rpx;

			.order-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-bottom: 20rpx;
				border-bottom: 2rpx solid #F5F5F5;

				.order-no {
					font-size: 28rpx;
					color: #333333;
				}

				.order-status {
					font-size: 28rpx;

					&.status-0 {
						color: #2B87FF;
					}

					// 待付款
					&.status-1 {
						color: #2B87FF;
					}

					// 待发货
					&.status-2 {
						color: #FF9500;
					}

					// 待收货
					&.status-3 {
						color: #52C41A;
					}

					// 已完成
					&.status-4 {
						color: #999999;
					}

					// 已取消
				}
			}

			// 商品列表样式
			.product-list {
				padding: 20rpx 0;
				border-bottom: 2rpx solid #F5F5F5;

				.product-item {
					display: flex;
					padding: 16rpx 0;

					.product-image {
						width: 120rpx;
						height: 120rpx;
						border-radius: 8rpx;
						background-color: #f8f8f8;
						object-fit: contain;
						margin-right: 20rpx;
					}

					.product-info {
						flex: 1;

						.product-title {
							font-size: 28rpx;
							color: #333333;
							margin-bottom: 8rpx;
						}

						.product-spec {
							font-size: 24rpx;
							color: #666666;
							margin-bottom: 8rpx;
						}

						.product-price {
							font-size: 26rpx;
							color: #FF0000;
							font-weight: 500;
						}
					}
				}
			}

			.order-content {
				padding-top: 20rpx;

				.address-info,
				.receiver-info,
				.price-info,
				.time-info {
					display: flex;
					margin-bottom: 16rpx;
					font-size: 28rpx;

					.label {
						color: #666666;
						width: 140rpx;
					}

					.value {
						flex: 1;
						color: #333333;

						&.price {
							color: #2B87FF;
							font-weight: bold;
						}
					}
				}
			}
		}
	}

	.empty-tip {
		text-align: center;
		color: #999999;
		font-size: 28rpx;
		padding: 100rpx 0;
	}

	.order-footer {
		display: flex;
		justify-content: flex-end;
		padding-top: 20rpx;
		margin-top: 20rpx;
		border-top: 2rpx solid #F5F5F5;

		.cancel-btn {
			background: #FFFFFF;
			color: #666666;
			font-size: 28rpx;
			padding: 10rpx 30rpx;
			border-radius: 30rpx;
			border: 2rpx solid #DDDDDD;
			margin-right: 20rpx;

			&::after {
				border: none;
			}

			&:active {
				background: #F8F8F8;
			}
		}

		.pay-btn {
			background: #2B87FF;
			color: #FFFFFF;
			font-size: 28rpx;
			padding: 10rpx 30rpx;
			border-radius: 30rpx;
			border: none;
			box-shadow: 0 4rpx 8rpx rgba(43, 135, 255, 0.2);
			transition: all 0.3s ease;

			&::after {
				border: none;
			}

			&:active {
				transform: scale(0.96);
				background: #1A76EE;
			}
		}
	}

	.status-nav {
		display: flex;
		background: #FFFFFF;
		padding: 20rpx 30rpx;
		margin-bottom: 20rpx;
		white-space: nowrap;
		border-radius: 12rpx;

		.nav-item {
			display: inline-block;
			position: relative;
			padding: 15rpx 30rpx;
			margin: 0 10rpx;
			font-size: 28rpx;
			color: #666666;

			&.active {
				color: #2B87FF;
				font-weight: bold;
			}

			.active-line {
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 40rpx;
				height: 4rpx;
				background: #2B87FF;
				border-radius: 2rpx;
			}

			&:first-child {
				margin-left: 0;
			}

			&:last-child {
				margin-right: 0;
			}
		}
	}

	.debug-section {
		display: flex;
		justify-content: flex-end;
		padding-top: 20rpx;
		margin-top: 20rpx;
		border-top: 2rpx solid #F5F5F5;

		.debug-btn {
			background: #FFFFFF;
			color: #666666;
			font-size: 28rpx;
			padding: 10rpx 30rpx;
			border-radius: 30rpx;
			border: 2rpx solid #DDDDDD;
			margin-right: 20rpx;

			&::after {
				border: none;
			}

			&:active {
				background: #F8F8F8;
			}
		}
	}
</style>